<template>
<view>
	<view class="d-login">
		<view class="d-b">{{title}}</view>
		<form class="cl">
			
			<block v-for="(item, index) in zhucexuanxiang" :key="index">

				<view v-if="item =='username'" class="d-a">
					<image src="@/static/images/img/wo2.png"></image>
					<input name="username" placeholder="请输入用户名" v-model="username" id="username"/>
				</view>
				<view v-if="item =='phone'" class="d-a">
					<image src="@/static/images/img/wo2.png"></image>
					<input name="phone" placeholder="请输入手机号码" v-model="phone" id="phone"/>
				</view>
				<view v-if="item =='email'" class="d-a">
					<image src="@/static/images/img/wo2.png"></image>
					<input name="email" placeholder="请输入邮箱" v-model="email" id="email"/>
				</view>
				<view v-if="item =='name'" class="d-a">
					<image src="@/static/images/img/wo2.png"></image>
					<input name="name" placeholder="请输入名称" v-model="name" id="name"/>
				</view>
			</block>
			<view class="d-a">
				<image src="@/static/images/img/yz.png"></image>
				<input type="password" name="password" placeholder="请输入密码" v-model="password" id="password"/>
			</view>
			<view class="d-a">
				<image src="@/static/images/img/yz.png"></image>
				<input type="password" name="password2" placeholder="请输入密码" v-model="password2" id="password2"/>
				<!--view class="d-c">发送短信</view-->
			</view>
			
			
			<view class="d-xia-10">
				<u-checkbox-group
					v-model="xieyizhi"
					placement="column"
					@change="xieyijieguo"
					activeColor="red"
				>
					<u-checkbox
						:customStyle="{marginBottom: '8px'}"
						v-for="(item, index) in zhucexieyi"
						:key="index"
						:label="item.name"
						:name="item.value"
					>
					</u-checkbox>
				</u-checkbox-group>
			</view>
			
			<!--view class="d-d">未注册的手机号验证后将自动注册</view-->
			<button form-type="submit" @click="yonghulogin">确认注册</button>
			
		</form>
		
		<!--view class="d-f">登录即同意<text>用户协议</text></view-->
		<view class="d-e cl">
			<!-- #ifdef MP-WEIXIN-->
		    <view class="d-g-2" @click="xcxWxLogin">
				<image src="@/static/images/img/wx.png"></image>
				<view>微信</view>
		    </view>
			<!-- #endif -->
		    <view class="d-g-2" @click="D_goLogin">
		        <image src="@/static/images/img/wo2.png"></image>
		        <view>登录</view>
		    </view>
			<!--view class="d-g" @click="">
			    <image src="@/static/images/img/yz.png"></image>
			    <view>找密码</view>
			</view-->
			
		</view>
	</view>
	<view class="d-kuan d-xia-10 d-shangxia-100 d-dibu-50" >
		<u-row justify="space-between" gutter="10">
			<u-col span="4" offset="4">
				<u-button type="default" :hairline="true" :plain="true" shape="circle" icon="home" open-type="getUserInfo" text="返回首页" @click="index"></u-button>
			</u-col>
		</u-row>
	</view>
	
	<privacy ref="privacy" type="bottom" :refuse="refuse" />
</view>
</template>

<script>

var Api = require("../../utils/api.js");
var util = require("../../utils/util.js");

var wxApi = require("../../utils/wxApi.js");
var wxRequest = require("../../utils/wxRequest.js");
import config from "../../utils/config";
var pageCount = config.getPageCount;
var webSiteName = config.getWebsiteName;
var domain = config.getDomain;
const app = getApp();

export default {
  data() {
    return {
		title: '账号注册',
		isArticlesList: true,
		listStyle: config.getListStyle,
		shareTitle: config.getWebsiteName,
		pageTitle: '登录',
		articlesList: [],
		postype: "post",
		webSiteName: webSiteName,
		domain: domain,
		username: '',
		phone: '',
		email: '',
		name: '',
		password: '',
		password2: '',
		cur: 0,
		show: true,
		xieyizhi:[], //协议值
		// 基本案列数据
		zhucexieyi: [{
				name: '用户注册协议',
				value:'1',
				//disabled: false,
			}
		],
		zhuce:{},
		zhucexuanxiang:[]
    };
  },

  components: {},
  props: {},
  mounted() {
  	let _this = this
  	if (wx.getPrivacySetting){
  	    wx.getPrivacySetting({
  	        success: (res) => {
  	            console.log(res)
  	            if (res.needAuthorization){
  	                _this.$refs.privacy.open()
  	            }
  	
  	            // 返回结果为: res = { needAuthorization: true/false, privacyContractName: '《xxx隐私保护指引》' }
  	        },
  	        fail: () => {},
  	        complete:() => {}
  	    })
  	}
  	
  },
  onShow: function () {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
	  var duixin = this;
	//判断用户是否登录
	var userInfo = uni.getStorageSync('userInfo');
	if (userInfo) {
		this.$router.push({ path: '/pages/wo/wo' }) // 跳转到会员页面
	} else {
		//否则跳转到登录页面
		/*uni.navigateTo({
			url: '/pages/login/login'
		});*/
		//this.$router.push({ path: '/pages/login/login' }) // 跳转到登录页面
	}
    var postype = 'post';

    if (options.postype) {
      postype = options.postype;
    }
	duixin.zhucexiangmu();

    this.setData({
      postype: postype
    });
  },
  onReady: function () {
    uni.setNavigationBarTitle({
      title: this.pageTitle
    });
  },
  methods: {
	refuse() {
	    // this.$refs.privacy.open()
	    uni.showToast({
	        icon: 'none',
	        title: '非常抱歉无法为您提供服务，如需服务请先同意相关协议~',
			   duration: 3000
	    });
	    return
	},
	index() {
		uni.switchTab({
			url: '/pages/index/index' // 目标页面的路径
		});
	},
    // 用户名登录
	async yonghulogin() {
		try {
			var self = this;
			self.setData({
			  data: []
			});
			var username = this.username; //账号
			var name = this.name; //账号
			var password = this.password; //密码
			var password2 = this.password2; //确认密码2
			var email = this.email; //邮箱可选
			var phone = this.phone; //手机号码可选
			var protocol = this.xieyizhi[0]; //是否同意协议
			//console.log("ooo",protocol);
			var datas = "is_ajax=1&is_protocol=1&data[password]="+password+"&data[password2]="+password2+"&is_protocol="+protocol;
			var zhuce = self.zhucexuanxiang;
			//console.log('zhucezhuce',zhuce);
			for (var i = 0; i < zhuce.length; i++) {
				//console.log('zhucedata'+[i],zhuce[i]);
				if(zhuce[i] == 'username'){
					datas += '&data[username]=' + username;
				}
				if(zhuce[i] == 'phone'){
					datas += '&data[phone]=' + phone;
				}
				if(zhuce[i] == 'email'){
					datas += '&data[email]=' + email;
				}
				if(zhuce[i] == 'name'){
					datas += '&data[name]=' + name;
				}
			}
			
			var datas;
			//console.log('datas',datas);
			//var datas = "is_ajax=1&is_protocol=1&data[username]="+username+"&data[password]="+password+"&data[password2]="+password2+"&data[email]="+email+"&data[phone]="+phone+"&is_protocol="+protocol;
			//邮箱+手机号
			var postYonghuRegisterRequest = wxRequest.postRequest(Api.postYonghuRegiste(),datas);
			postYonghuRegisterRequest.then(response => {
					if (response.data.code == 1) {
					  console.log(response.data.data); 
					  self.data = response.data.auth; 
					    // 保存用户信息到本地storage
					    uni.setStorageSync('userInfo', response.data.data.member.auth);
						uni.setStorageSync('memberuid', response.data.data.member.id);
						uni.setStorageSync('member', response.data.data.member);
						uni.setStorageSync('keycode', response.data.data.auth);
						//登录跳转到登录页面
						uni.reLaunch({ url: "/pages/wo/wo" });
					} else {
					  //self.setData({
						//displaySwiper: "none"
					  //});
					  uni.showToast({
					  	icon: 'none',
					  	title: response.data.msg,
					  });
					}
				});

			} catch (error) {
				console.error(error);
				uni.showToast({
					icon: 'none',
					title: '注册失败，请稍后重试'
				});
			}
			
	},
	async xcxWxLogin() {
		try {
			uni.showToast({
				title: "正在登录...",
				icon: 'loading',
				success: function () {
				}
			});
			uni.login({
			    success: function (res) {
			        console.log(res);
					uni.showToast({
					    title: "登录中...",
					    icon: 'clear',
					});
			        if (res.code) {
			            uni.getUserInfo({
			                success: function (userRes) {
			                    //发起网络请求D
			                    uni.request({
			                        url: Api.getWwwUrl()+"s=weixin&c=member&m=xcx",
			                        data: {
			                            json: userRes.rawData,
			                            js_code: res.code
			                        },
			                        method: 'post',
			                        header: {
			                            'Content-Type': 'application/x-www-form-urlencoded',
			                        },
			                        success: function (res) {
			                            console.log(res.data);
			                            if (res.data.code) {
			                                if (res.data.msg == 'login') {
												uni.showToast({
												    title: "登录成功",
												    icon: 'success',
												    success: function () { 
												    }
												});
			                                    // 登录成功
			                                    console.log("登录成功了");
			                                    uni.setStorageSync('memberuid', res.data.data.member.id);
			                                    uni.setStorageSync('userInfo', res.data.data.auth);
			                                    uni.setStorageSync('member', res.data.data.member);
			                                    uni.setStorageSync('keycode', res.data.data.auth);
												// 跳转新页面
												setTimeout(() => {
												    uni.reLaunch({ url: "/pages/wo/wo" });
												}, 1000);
			
			                                } else {
			                                    // 绑定账号注册
			                                    uni.showModal({
			                                        showCancel: false,
			                                        content: "后台微信插件中需要开启直接登录模式"
			                                    })
			                                }
			                            } else {
			                                // 失败了
			                                uni.showModal({
			                                    showCancel: false,
			                                    content: res.data.msg
			                                })
			                            }
			                        }
			                    });
			
			
			                }
			            });
			        } else {
			            console.log('登录失败：' + res.errMsg)
			        }
			    }
			});
			
		} catch (error) {
				console.error(error);
				uni.showToast({
					icon: 'none',
					title: '登录失败，请稍后重试'
				});
			}
	},
	async xcxWxBangding() {
		try {
			uni.login({
			    success: function (res) {
			        console.log(res);
			        if (res.code) {
			            uni.getUserInfo({
			                success: function (userRes) {
			                    //发起网络请求D
			                    uni.request({
			                        url: Api.getWeixinBangding(),
			                        data: {
			                            json: userRes.rawData,
			                            js_code: res.code
			                        },
			                        method: 'post',
			                        header: {
			                            'Content-Type': 'application/x-www-form-urlencoded',
			                        },
			                        success: function (res) {
			                            console.log(res.data);
			                            if (res.data.code) {
			                                if (res.data.msg == 'login') {
			                                    // 登录成功
			                                    console.log("登录成功了");
			                                    uni.setStorageSync('memberuid', res.data.data.member.id);
			                                    uni.setStorageSync('userInfo', res.data.data.auth);
			                                    uni.setStorageSync('member', res.data.data.member);
												uni.setStorageSync('keycode', res.data.data.auth);
			                                    uni.showToast({
			                                        title: "登录成功",
			                                        icon: 'success',
			                                        success: function () {
			                                            // 跳转新页面
			                                            uni.reLaunch({ url: "/pages/wo/wo" });
			                                        }
			                                    })
			
			                                } else {
			                                    // 绑定账号注册
			                                    uni.showModal({
			                                        showCancel: false,
			                                        content: "后台微信插件中需要开启直接登录模式"
			                                    })
			                                }
			                            } else {
			                                // 失败了
			                                uni.showModal({
			                                    showCancel: false,
			                                    content: res.data.msg
			                                })
			                            }
			                        }
			                    });
			
			
			                }
			            });
			        } else {
			            console.log('登录失败：' + res.errMsg)
			        }
			    }
			});
			
		} catch (error) {
				console.error(error);
				uni.showToast({
					icon: 'none',
					title: '登录失败，请稍后重试'
				});
			}
	},
	D_goLogin() {
		uni.navigateTo({
			url: '/pages/login/login' // 目标页面的路径
		});
	},
	//协议结果
	xieyijieguo(n) {
		this.xieyizhi = n;
		//console.log('change', n);
	},
	//注册项目
	zhucexiangmu(){
		var duixin = this;
		var postYonghuzhuceRequest = wxRequest.getRequest(Api.postYonghuRegiste());
		postYonghuzhuceRequest.then(response => {
			if (response.data.code == 1) {
			    duixin.zhuce = response.data.data;
				duixin.zhucexuanxiang = duixin.zhuce.register && duixin.zhuce.register.field;
				//console.log('duixin.zhuce', duixin.zhuce.register && duixin.zhuce.register.field);
			} else {
			  
			}
		});
	}
  }
};
</script>
<style lang="scss">
@import "./login.css";
page {
	background-color: #f3f4f7;
}

</style>